<?php
/**
 * Created by PhpStorm.
 * User: wangjie
 * Date: 2020/07/27
 * Time: 下午5:13
 */
namespace App\Api\Controllers\Cmbc;

use App\Api\Controllers\BaseController;
use App\Common\PaySuccessAction;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use App\Api\Controllers\Cmbc\BaseController as base;

class NotifyController extends BaseController{

    public function pay_notify_url(Request $request){
        try {
            $data = $request->all();
            //Log::channel('daily')->debug(sprintf("== 银卡主扫回调 请求 ==\n【回调】%s\n", json_encode($data)));
            error_log(date('Y-m-d H:i:s')." 【民生主扫回调】： ".json_encode($data)."\n\n", 3, "/tmp/". 'cmbc'.date('Ymd').".log");

            $payStore = DB::table("cmbc_stores")->where('mch_id', $data['mch_id'])->first();
            $base = base::getInstance();
            $ret  = json_decode($base::decryptContext($data['context'], [
                'base64P12Data'  => $payStore->private_key,
                'base64CertSignAlg' => 'SM4/CBC/PKCS7Padding',
                'P12Password'  => '123abc'
            ]), true);
            if (isset($ret['body']) && !empty($ret['body'])) {
                error_log(date('Y-m-d H:i:s')." 【民生主扫回调】： ".json_encode([$ret['body']])."\n\n", 3, "/tmp/". 'cmbc'.date('Ymd').".log");
                $return = json_decode($ret['body'], true);

                if (isset($return['tradeStatus']) && $return['tradeStatus'] == 'S') {

                    if (isset($return['mchSeqNo'])) {
                        $out_trade_no = $return['mchSeqNo']; //商户订单号（原交易流水）
                        $trade_no = $return['centerSeqId']; //系统订单号

                        $day = date('Ymd', time());
                        $table = 'orders_' . $day;
                        if (Schema::hasTable($table)) {
                            $order = DB::table($table)->where('out_trade_no', $out_trade_no)->first();
                        } else {
                            $order = Order::where('out_trade_no', $out_trade_no)->first();
                        }

                        //订单存在
                        if ($order) {
                            //系统订单未成功
                            if ($order->pay_status == '2') {

                                $centerInfo = explode('|', $return['centerInfo']);
                                $buyer_id = '';
                                if (isset($centerInfo['buyer_id'])) {
                                    $buyer_id = $centerInfo['buyer_id'];
                                }
                                $pay_time = date('Y-m-d H:i:s', strtotime($return['transDate'].$return['transTime']));
                                //$buyer_pay_amount = number_format($return['amount'] * 100, 0, '.', '');
                                $buyer_pay_amount = $return['amount'] * 0.01;

                                $in_data = [
                                    'status' => '1',
                                    'pay_status' => 1,
                                    'pay_status_desc' => '支付成功',
                                    'trade_no' => $trade_no,
                                    'pay_time' => $pay_time,
                                    'buyer_id' => $buyer_id,
                                    'buyer_pay_amount' => $buyer_pay_amount,
                                ];

                                $this->update_day_order($in_data, $out_trade_no);

                                if (strpos($out_trade_no, 'scan')) {

                                } else {
                                    //支付成功后的动作
                                    $data = [
                                        'ways_type' => $order->ways_type,
                                        'company' => $order->company,
                                        'ways_type_desc' => $order->ways_type_desc,
                                        'source_type' => '21000', //返佣来源
                                        'source_desc' => '易生支付', //返佣来源说明
                                        'total_amount' => $order->total_amount,
                                        'out_trade_no' => $order->out_trade_no,
                                        'other_no' => $order->other_no,
                                        'rate' => $order->rate,
                                        'fee_amount' => $order->fee_amount,
                                        'merchant_id' => $order->merchant_id,
                                        'store_id' => $order->store_id,
                                        'user_id' => $order->user_id,
                                        'config_id' => $order->config_id,
                                        'store_name' => $order->store_name,
                                        'ways_source' => $order->ways_source,
                                        'pay_time' => $pay_time,
                                        'device_id' => $order->device_id,
                                    ];
                                    PaySuccessAction::action($data);
                                }
                            }
                        }
                    }
                    return 'SUCCESS';
                } else {
                    Log::info('易生-支付回调-结果');
                    Log::info($data);
                }

            }
        } catch (\Exception $ex) {
            echo $ex->getMessage().$ex->getLine();
        }
    }


    

}
